import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/aes_util.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/login/forget_password.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/module/frame_page.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '随手拍',
      theme: ThemeData(primaryColor: Colors.white),
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return LoginPageState();
  }
}

class LoginPageState extends State<LoginPage> {
  String animationType = "idle";
  final passFocusNode = FocusNode();
  final userFocusNode = FocusNode();
  TextEditingController _userNameController = new TextEditingController();
  TextEditingController _passwordController = new TextEditingController();
  bool passwordVisible = true;

  @override
  void initState() {
    super.initState();
    passFocusNode.addListener(() {
      if (passFocusNode.hasFocus) {
        setState(() {
          animationType = "hands_up";
        });
      } else {
        setState(() {
          animationType = "hands_down";
        });
        Future.delayed(Duration(milliseconds: 500), () {
          setState(() {
            animationType = "idle";
          });
        });
      }
    });
  }

  void hindKeyBoarder() {
    //输入框失去焦点
    passFocusNode.unfocus();
    userFocusNode.unfocus();
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GestureDetector(
      child: Stack(
        children: <Widget>[
          Container(
            height: 300,
            color: greyF3F3F3,
            padding: EdgeInsets.only(top: 60, bottom: 30),
            child: FlareActor('assets/Teddy.flr',
                shouldClip: false,
                alignment: Alignment.bottomCenter,
                fit: BoxFit.contain,
                animation: animationType),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            margin: EdgeInsets.only(top: 270),
            decoration: BoxDecoration(
              borderRadius: borderRadiusOnlyLeftTop24(),
              color: Colors.white,
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 36, horizontal: 44),
              child: ListView(
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.only(bottom: 24),
                    child: Text(
                      '登录',
                      textAlign: TextAlign.left,
                      style:
                          TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Container(
                      height: 54,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: borderRadiusAll8(),
                        color: greyF6F6F6,
                      ),
                      child: TextFormField(
                        focusNode: userFocusNode,
                        controller: _userNameController,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: '账号',
                            prefixIcon: Icon(Icons.person_outline),
                            hintStyle:
                                TextStyle(fontSize: 18, color: Colors.grey)),
                        style: TextStyle(fontSize: 18),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Container(
                      height: 54,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: borderRadiusAll8(),
                        color: greyF6F6F6,
                      ),
                      child: TextFormField(
                        obscureText: passwordVisible,
                        controller: _passwordController,
                        maxLines: 1,
                        focusNode: passFocusNode,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '密码',
                          prefixIcon: Icon(Icons.lock_outline),
                          hintStyle:
                              TextStyle(fontSize: 18, color: Colors.grey),
                          suffixIcon: IconButton(
                            icon: Icon(
                              //根据passwordVisible状态显示不同的图标
                              passwordVisible
                                  ? Icons.visibility
                                  : Icons.visibility_off,
                              color: Theme.of(context).primaryColorDark,
                            ),
                            onPressed: () {
                              //更新状态控制密码显示或隐藏
                              setState(() {
                                passwordVisible = !passwordVisible;
                              });
                            },
                          ),
                        ),
                        style: TextStyle(fontSize: 18),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 30),
                    child: MaterialButton(
                      onPressed: () {
                        _submitLogin();
                      },
                      child: Text(
                        '登录',
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                            letterSpacing: 2),
                      ),
                      color: Colors.blueAccent,
                      elevation: 0,
                      minWidth: 400,
                      height: 54,
                      textColor: Colors.white,
                      shape: RoundedRectangleBorder(
                          borderRadius: borderRadiusAll8()),
                    ),
                  ),
                  Container(
                      padding:
                          EdgeInsets.symmetric(vertical: 30, horizontal: 60),
                      child: TextButton(
                        onPressed: () {
                          Navigator.push(
                              context,
                              new MaterialPageRoute(
                                  builder: (context) => ForgetPasswordPage()));
                        },
                        child: Text(
                          '忘记密码？',
                          style: TextStyle(
                              fontSize: 16,
                              color: greyCCCCCC,
                              fontWeight: FontWeight.bold),
                        ),
                      ))
                ],
              ),
            ),
          ),
        ],
      ),
      onTap: () {
        hindKeyBoarder();
      },
    ));
  }

  void _submitLogin() async {
    String username = _userNameController.text;
    String password = _passwordController.text;
    _userNameController.clear();
    _passwordController.clear();

    HttpRequest.request("$BASE_URL/employee/login", method: "post", data: {
      "employeeId": AesUtil.aesEncrypt(username),
      "password": AesUtil.aesEncrypt(password)
    }).then((value) {
      print(value);
      if (value.data["code"] == 200) {
        setState(() {
          animationType = "success";
        });
        Future.delayed(Duration(milliseconds: 1000), () async {
          Navigator.of(context).pushAndRemoveUntil(
              new MaterialPageRoute(builder: (context) => new FramePage()),
              (route) => route == null);
          setState(() {
            animationType = "idle";
          });
          StorageUtil.setStringItem("employeeId", username.toString());
          print(value.data["result"]["role"]);
          StorageUtil.setStringItem("role", value.data["result"]["role"]);
        });
        Fluttertoast.showToast(msg: "登录成功");
      } else {
        setState(() {
          animationType = "fail";
        });
        Future.delayed(Duration(milliseconds: 3000), () {
          setState(() {
            animationType = "idle";
          });
        });
        Fluttertoast.showToast(msg: "用户名或密码错误");
      }
    });
  }
}
